package org.demo.test.thread._volatile;

import java.util.ArrayList;
import java.util.List;

public class VolatileObject {

    List list = new ArrayList<>();

    /**
     * volatile对对象类型中的内容也是能够生效的
     */
    volatile RunningObject vo = new RunningObject();

    class RunningObject{

//        volatile boolean running = true;
        boolean running = true;
    }

    public void add(Object o){
        list.add(o);
    }

    public int size(){
        return list.size();
    }

    void m(){
        while (vo.running){
        }
        System.out.println("M退出");
    }

    public static void main(String[] args) {
        VolatileObject volatileObject = new VolatileObject();

        new Thread(()->{
            volatileObject.m();
        }).start();

        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("置为停止");
        volatileObject.vo.running = false;

        /*new Thread(()->{
            boolean flag = true;
            while (flag){
                if(volatileObject.size() == 5){
                    flag = false;
                }
            }
            System.out.println("====5====");
        }).start();

        new Thread(()->{
            for (int i=0; i < 10; i++){
                volatileObject.add(new Object());
            }
        }).start();*/
    }
}
